package com.jwsoft.manager.core.dao.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bifang.engine.assistant.core.enums.AuthStatusEnum;
import com.bifang.engine.assistant.core.enums.BoolEnum;
import com.bifang.engine.assistant.core.exception.AppException;
import com.bifang.module.base.common.util.CommonSecureUtil;
import com.jwsoft.manager.common.enums.EduStatusTypeEnum;
import com.jwsoft.manager.common.vo.eduDataTaskDetail.DataTaskDetailOptionVO;
import com.jwsoft.manager.common.vo.eduHouse.EduHouseQueryVO;
import com.jwsoft.manager.common.vo.eduHouse.EduHouseVO;
import com.jwsoft.manager.core.dao.mapper.EduhHouseMapper;
import com.jwsoft.manager.core.dao.mapper.EdutHouseMapper;
import com.jwsoft.manager.core.dao.model.*;
import com.jwsoft.manager.core.dao.mapper.EduHouseMapper;
import com.jwsoft.manager.core.dao.service.EduDataTaskDetailService;
import com.jwsoft.manager.core.dao.service.EduHouseService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jwsoft.manager.core.dao.service.TableService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionCallbackWithoutResult;
import org.springframework.transaction.support.TransactionTemplate;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 服务实现类
 *
 * @author wangtao
 * @since 2022-11-30
 */
@Service
@Slf4j
public class EduHouseServiceImpl extends ServiceImpl<EduHouseMapper, EduHouse> implements EduHouseService, TableService {

    @Autowired
    private EduDataTaskDetailService detailService;

    @Autowired
    private TransactionTemplate transactionTemplate;

    @Autowired
    private EduhHouseMapper hHouseMapper;

    @Autowired
    private EdutHouseMapper tHouseMapper;


    private static final String HOUSE_TABLE = "edu_house";

    //每次处理的数量为1w条数据
    private static final Integer PAGE_SIZE = 10000;

    @Override
    public List<EduHouse> getUseList(int year, int limitYear, String areaCode,String address, String realPropertyNum ) {
        return baseMapper.getUseList(year, limitYear, areaCode,address,realPropertyNum);
    }

    @Override
    public List<EduHouse> getHouseByAllIdcard(List<String> idcardList, int year) {
        return this.getHouseByAllIdcard(idcardList, year, BoolEnum.TRUE.getType(), AuthStatusEnum.YES.getType());
    }


    @Override
    public List<EduhHouse> getHouseByAllIdcardHistory(List<String> idcardList, int year) {
        return this.getHouseByAllIdcardHistory(idcardList, year, BoolEnum.TRUE.getType(), AuthStatusEnum.YES.getType());
    }

    @Override
    public List<EduHouse> getHouseByAllIdcard(List<String> idcardList, int year, String status, String authStatus) {
        return this.baseMapper.getHouseByAllIdcard(idcardList, year, status, authStatus);
    }

    @Override
    public List<EduhHouse> getHouseByAllIdcardHistory(List<String> idcardList, int year, String status, String authStatus) {
        return this.baseMapper.getHouseByAllIdcardHistory(idcardList, year, status, authStatus);
    }
    @Override
    public EduHouse getHouseById(String houseId) {
        return baseMapper.getHouseById(houseId);
    }

    @Override
    public List<EduHouseVO> gethouseByPropertyNumAndIDcard(EduHouseQueryVO vo) {
        return baseMapper.gethouseByPropertyNumAndIDcard(vo);

    }

    /**
     * 查询条件加密
     * @param vo
     */
    @Override
    public void queryEncrypt(EduHouseQueryVO vo) {
        if (StringUtils.isNotBlank(vo.getAddress())) {
            vo.setAddress(CommonSecureUtil.sm4Encrypt(vo.getAddress()));
        }
        if (StringUtils.isNotBlank(vo.getQlrName())) {
            vo.setQlrName(CommonSecureUtil.sm4Encrypt(vo.getQlrName()));
        }
    }


    /**
     * 用于处理相关EduHouse表中的数据
     * 1.处理数据迁移 dataMigration
     * 2.处理数据加密
     * 3.处理数据销毁
     */
    @Override
    public Integer dataMigration(DataTaskDetailOptionVO optionVO) {
        EduDataTaskDetail taskDetail = detailService.getById(optionVO.getTaskDetailId());
        log.info("调用了EduHouseServiceImpl服务的dataMigration()来进行处理迁移数据");
        Integer count = this.baseMapper.selectCountByYear(optionVO.getYear());
        log.info("edu_house迁移" + count + "条数据");
        int totalPages = (count % PAGE_SIZE == 0) ? (count / PAGE_SIZE) : (count / PAGE_SIZE + 1);
        for (int i = 0; i < totalPages; i++) {
            List<EduHouse> eduHouseList =
                    this.baseMapper.selectByYear(optionVO.getYear(), PAGE_SIZE);
            if (eduHouseList.size() > 0) {
                List<EduhHouse> hHouseList = eduHouseList.stream().map(eduHouse -> {
                    EduhHouse hHouse = new EduhHouse();
                    BeanUtils.copyProperties(eduHouse, hHouse);
                    hHouse.setTaskDetailId(taskDetail.getTaskDetailId());
                    hHouse.setEncryptFlag(BoolEnum.FALSE.getType());
                    hHouse.setEncryptStatus(EduStatusTypeEnum.dcl.getType());
                    hHouse.setCleanFlag(BoolEnum.FALSE.getType());
                    return hHouse;
                }).collect(Collectors.toList());
                try {
                    this.performDataMigration(hHouseList, eduHouseList.size() , optionVO);
                } catch (Exception e) {
                    log.error("edu_house迁移数据发生异常");
                    throw new RuntimeException("EduHouseServiceImpl:" + e);
                }
            }
        }
        return count;
    }

    private Integer performDataMigration(List<EduhHouse> hHouseList, Integer count, DataTaskDetailOptionVO optionVO) {
        Integer result = transactionTemplate.execute(new TransactionCallback<Integer>() {
            @Override
            public Integer doInTransaction(TransactionStatus status) {
                try {
                    //1.数据迁移到历史表
                    int saveHCount = hHouseMapper.saveBatch(hHouseList);
                    if (saveHCount != count) {
                        throw new RuntimeException("数据迁移到历史表失败");
                    }
                    //2.数据销毁
                    EduDataTaskDetail taskDetail = detailService.getById(optionVO.getTaskDetailId());
                    if (ObjectUtils.isEmpty(taskDetail)) {
                        throw new AppException("任务数据不存在，请检查数据是否有误");
                    }
                    Integer deleteCount = baseMapper.deleteByTaskHistory(taskDetail.getTaskDetailId());
                    if (!count.equals(deleteCount)) {
                        throw new RuntimeException("数据删除失败");
                    }
                    log.info("edu_house数据销毁成功！销毁数量：" + count);
                    return count;
                } catch (Exception e) {
                    status.setRollbackOnly();
                    throw e;
                }
            }
        });
        //返回处理的结果数量
        return result;
    }

    @Override
    public void dataEncryption(DataTaskDetailOptionVO optionVO) {
        EduDataTaskDetail taskDetail = detailService.getById(optionVO.getTaskDetailId());
        log.info("调用了EduHouseServiceImpl服务的dataEncryption()来进行处理数据加密");
        Integer count = 0;
        if (taskDetail.getEncryptCount() == 0) {
            count = this.baseMapper.selectEncryptionCountByYear(optionVO.getYear(), optionVO.getTaskDetailId());
            taskDetail.setEncryptCount(count);
        }
        Boolean errorFlag = false;
        Integer errorCount = 0;
        int totalPages = (count % PAGE_SIZE == 0) ? (count / PAGE_SIZE) : (count / PAGE_SIZE + 1);
        for (int i = 0; i < totalPages; i++) {
            List<EduhHouse> hHouses =
                    this.baseMapper.selectEncryptionByYear
                            (optionVO.getYear(), optionVO.getTaskDetailId(),PAGE_SIZE);
            for (EduhHouse hHouse : hHouses) {
                try {
                    this.encrypt(hHouse);
                    hHouse.setEncryptTime(new Date());
                    hHouse.setEncryptStatus(EduStatusTypeEnum.success.getType());
                    hHouse.setEncryptRemarks("加密成功");
                    hHouse.setEncryptFlag(BoolEnum.TRUE.getType());
                    //保存到数据库，可能成功，可能失败，失败就不加密
                    try {
                        hHouseMapper.updateById(hHouse);
                    }catch (Exception dbException) {
                        log.error("更新数据库失败，ID: {}, 错误信息: {}", hHouse.getHouseId(), dbException.getMessage());
                        // 不抛出异常，仅记录日志
                        continue;
                    }
                }catch (Exception e){
                    this.decrypt(hHouse);
                    hHouse.setEncryptTime(new Date());
                    hHouse.setEncryptStatus(EduStatusTypeEnum.error.getType());
                    hHouse.setEncryptFlag(BoolEnum.FALSE.getType());
                    hHouse.setEncryptRemarks("加密失败"+e.getMessage());
                    hHouseMapper.updateById(hHouse);
                    errorFlag = true;
                    errorCount++;
                    throw new AppException(e);
                }
            }
        }
        if (!errorFlag) {
            //无异常，返回任务状态
            taskDetail.setEncryptStatus(EduStatusTypeEnum.success.getType());
            taskDetail.setEncryptRemarks("加密成功");
            taskDetail.setEncryptTime(new Date());
        } else {
            taskDetail.setEncryptStatus(EduStatusTypeEnum.error.getType());
            taskDetail.setEncryptTime(new Date());
            taskDetail.setEncryptRemarks(taskDetail.getHandleTable()
                    +"加密失败,加密出错的数据：" + errorCount);
        }
        detailService.updateById(taskDetail);
    }

    /**
     * 房产数据加密
     *
     * @param hHouse
     */
    private void encrypt(EduhHouse hHouse) {
        if (StringUtils.isNotBlank(hHouse.getAddress())) {
            hHouse.setAddress(CommonSecureUtil.sm4Encrypt(hHouse.getAddress()));
        }
        if (StringUtils.isNotBlank(hHouse.getQlrName())) {
            hHouse.setQlrName(CommonSecureUtil.sm4Encrypt(hHouse.getQlrName()));
        }
    }

    /**
     * 房产数据解密
     * @param hHouse
     */
    private void decrypt(EduhHouse hHouse) {
        if (StringUtils.isNotBlank(hHouse.getAddress())) {
            hHouse.setAddress(CommonSecureUtil.sm4Decrypt(hHouse.getAddress()));
        }
        if (StringUtils.isNotBlank(hHouse.getQlrName())) {
            hHouse.setQlrName(CommonSecureUtil.sm4Decrypt(hHouse.getQlrName()));
        }
    }

    @Override
    public Integer dataDestruction(DataTaskDetailOptionVO optionVO) {
        EduDataTaskDetail taskDetail = detailService.getById(optionVO.getTaskDetailId());
        log.info("调用了EduHouseServiceImpl服务的dataDestruction来进行处理数据清洗");
        //房产数据销毁规则：报名表中有houseId，使用过的房产数据 保留
        //判断指定的年度的报名数据是否执行过迁移
        Boolean queryHistory =
                detailService.verifyQueryHistory(optionVO.getYear(), HOUSE_TABLE);
        List<EduhHouse> hHouses = new ArrayList<>();
        if (queryHistory){
            //从历史报名数据，查出需要清除的房产数据
            hHouses = this.baseMapper.queryHistoryCleanHouseWithEnroll
                    (taskDetail.getYear(),taskDetail.getTaskDetailId());
        }else{
            //从在线报名数据，查出需要清除的房产数据
            hHouses = this.baseMapper.queryCleanHouseWithEnroll(optionVO.getYear(),taskDetail.getTaskDetailId());
        }
        Integer cleanCount = hHouses.size();
        if (cleanCount != 0){
            try {
                this.preformDataClean(hHouses,cleanCount);
            } catch (Exception e) {
                log.error("eduh_house数据清洗发生异常");
                throw new RuntimeException("EduHouseServiceImpl:" + e);
            }
        }
        return cleanCount;
    }

    /**
     * 执行数据清洗
     * @param hHouses
     * @param cleanCount
     */
    private void preformDataClean(List<EduhHouse> hHouses,Integer cleanCount) {
        transactionTemplate.execute(new TransactionCallbackWithoutResult() {
            @Override
            protected void doInTransactionWithoutResult(TransactionStatus status) {
                try {
                    List<EdutHouse> tHouseList = hHouses.stream().map(item -> {
                        EdutHouse edutHouse = new EdutHouse();
                        BeanUtils.copyProperties(item,edutHouse);
                        edutHouse.setCleanFlag(BoolEnum.TRUE.getType());
                        return edutHouse;
                    }).collect(Collectors.toList());
                    //需要删除的数据迁移到临时表中
                    tHouseMapper.saveBatch(tHouseList);
                    //根据id进行删除历史表中的数据
                    Integer count = 0;
                    for (EduhHouse hHouse : hHouses) {
                        count ++;
                        hHouseMapper.deleteHistoryById(hHouse.getHouseId());
                    }
                    if (count != cleanCount){
                        throw new AppException("要清洗的数据为："+cleanCount+",清洗的数据为："+count+"数据量不一致，请检查后重试！");
                    }
                } catch (Exception e) {
                    status.setRollbackOnly();
                    throw e;
                }
            }
        });
    }

    @Override
    public void tempDataDestruction() {
        System.out.println("空闲数据销毁");
    }

    /**
     * 数据解密恢复到临时表
     *
     * @param optionVO
     */
    @Override
    public void dataDecrypt(DataTaskDetailOptionVO optionVO) {
        Integer count = Math.toIntExact(hHouseMapper.selectCount(new QueryWrapper<EduhHouse>().lambda().eq(EduhHouse::getTaskDetailId, optionVO.getTaskDetailId())));
        int totalPages = (count % PAGE_SIZE == 0) ? (count / PAGE_SIZE) : (count / PAGE_SIZE + 1);
        int currentPage = 0;
        for (int i = 0; i < totalPages; i++) {
            List<EduhHouse> eduhHouses =  hHouseMapper.selectByTaskDetailId(optionVO.getTaskDetailId(),currentPage,PAGE_SIZE);
            List<EdutHouse> tHouses = eduhHouses.stream().map(eduhHouse -> {
                if (BoolEnum.TRUE.getType().equalsIgnoreCase(eduhHouse.getEncryptFlag())) {
                    //需要进行解密
                    this.decrypt(eduhHouse);
                }
                EdutHouse tHouse = new EdutHouse();
                BeanUtils.copyProperties(eduhHouse, tHouse);
                return tHouse;
            }).collect(Collectors.toList());
            tHouseMapper.saveBatch(tHouses);
            currentPage = i + 1;
        }
    }
}
